<!DOCTYPE html>
<html>

<head>
    <title> Lists and Keys </title>
    <script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js" crossorigin></script>
</head>

<body>
    <div id="root"></div>
</body>

</html>
<script type="text/babel">
    /**
    Keys
    Keys help React identify which items have changed, are added, or are removed.
    Keys should be given to the elements inside the array to give the elements a stable identity.
    */

    // Way 1 : Add key
    // function NumberList(props) {
    //     const numbers = props.numbers;
    //     const listItems = numbers.map((item) =>
    //         <li key={item.toString()}>{item}
    //         </li>);
    //     return (<ul>{listItems}</ul>);
    // }
    // const numbers = [1, 2, 3, 4, 5];

    /**
        Way 2 : Add key: Key is ID.
        The best way to pick a key is to use a string that uniquely identifies a list item among it's siblings.
        Most offten use IDs IDs from data as keys.
    */

    // function NumberList(props) {
    //     const numbers = props.numbers;
    //     const listItems = numbers.map((item) =>
    //         <li key={item.id}>{item.text}
    //         </li>);
    //     return (<ul>{listItems}</ul>);
    // }
    // const numbers = [
    //     { id: "id_1", text: "1" },
    //     { id: "id_2", text: "2" },
    //     { id: "id_3", text: "3" },
    //     { id: "id_4", text: "4" },
    //     { id: "id_5", text: "5" }];

    /*
    Way 3 : Add Key: Key is index
    Add key: don't have stableIDS for rendered items, we can use item index as a key as a last resort.

    We don’t recommend using indexes for keys if the order of items may change. 
    This can negatively impact performance and may cause issues with component state. 
    If you choose not to assign an explicit key to list items then React will default to using indexes as keys.
    */
    function NumberList(props) {
        const numbers = props.numbers;
        const listItems = numbers.map((item, index) =>
            // Only do this if items have no stable IDs.
            <li key={index}>{item.text}
            </li>);
        return (<ul>{listItems}</ul>);
    }
    const numbers = [
        { text: "text_1" },
        { text: "text_2" },
        { text: "text_3" },
        { text: "text_4" },
        { text: "text_5" }];
    ReactDOM.render(<NumberList numbers={numbers} />, document.getElementById('root'));
</script>